package socket;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 聊天室客户端
 *
 */

public class Client {

    private Socket socket;

    public Client(){


        try {

            System.out.println("正在连接服务端...");

            socket = new Socket("176.212.29.211",8088);

            System.out.println("与服务端建立了连接！");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public void start(){
        try {
            //启动用于读取服务端发送过来消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();

            /*
            Socket提供的方法：


             */






            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out,"UTF-8");

            BufferedWriter bw = new BufferedWriter(osw);

            PrintWriter pw = new PrintWriter(bw,true);



            Scanner scan = new Scanner(System.in);
            while(true){
                String line = scan.nextLine();
                if("exit".equals(line)){
                    break;
                }
                pw.println(line);

            }

//            pw.println("你好服务端！");



        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try{
                socket.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }


    public static void main(String[] args) throws IOException {
        Client client = new Client();
        client.start();
    }

    /**
     *该线程负责循环读取服务端发送过来的消息
     */

    private class ServerHandler implements Runnable{
        public void run(){
            //通过socket获取输入流读取服务端发送过来的消息
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }



}
